jQuery(document).ready(function($){

var fw_sc = sc = 
{
	gender : 'man', view : 'front', selected : {}, symptoms : sc_data,
	
	init : function()
	{
		$('#sc_gender').change(function(){
			sc.gender = $(this).val();
			sc.update_list('list-1', sc.gender+'.'+sc.view, true);
		});
		
		$('#sc_gender').trigger('change');
		
		$('#gender-view > a').click(function(){
			sc.view = ($(this).attr('class') == 'back') ? 'back' : 'front';
			sc.update_list('list-1', sc.gender+'.'+sc.view);
			return false;
		});
		
		$('.multiselect-checkboxes').on('click', '.sc_option', function(e){
			if($(e.target).attr("class") == 'icon-trash' || $(e.target).attr("class") == 'icon-edit' || $(this).find('.edit_value').length) return;
			
			var list = $(this).parent().attr('id'), next = sc.listID(list) + 1;
			if(next > 4) return false;
			
			$(this).siblings().find('label').removeClass();
			$(this).children('label').addClass('focused');
			
			sc.unselect(next + 1);
			
			sc.selected[list] = $(this).find('label > span').text();
			sc.update_list('list-'+next, $(this).attr('id'));
		});
		
		//$('.icon-trash').live('click', function(){
		$('.multiselect-checkboxes').on('click', '.icon-trash', function(){
			var ul = $(this).parents('ul:first').attr('id');
			var li = $(this).parents('li');
			var index = $(li).index();
			var key = $('span', li).text();
			if( ! key) return;
	
			sc.del_value(key, sc.get_path(ul));
			sc.update_list(ul, sc.get_path(ul));
			
			if($('#'+ul+' > li').length) if(index) $(li).next().trigger('click'); else $(li).prev().trigger('click');
			else sc.unselect(sc.listID(ul) + 1);
		});
		
		$('.add-value').bind('keypress', function(e){
			if(e.keyCode==13){
				$(this).siblings('.add-option').trigger('click');
			}
		});
	
		$('.add-option').click(function(){
			var ul = $(this).parent().siblings('ul:first').attr('id'), myID = parseInt(sc.listID(ul));
			var parent = (myID) ? 'list-1' : 'list-'+(myID - 1);
			
			if(ul != 'list-1' && undefined == sc.selected[parent])
				return sc._msg('Please select the value in list "<strong>'+$('#'+parent).prev('.select-title').text()+'</strong>" first.');
			
			var input = $(this).siblings('.add-value:first')
			var New = $(input).val();
			if( ! New) return sc._msg('Please enter a valid string in add box to add.');
			
			if(sc.add_value(New, sc.get_path(ul))){
				//sc.symptoms['testing'] = {};
				sc.update_list(ul, sc.get_path(ul));
				$(input).val('');
				$('#'+ul).scrollTop($('#'+ul).height())
				$('#'+ul+' > li:last').trigger('click');
			}
		});
		
		$('.icon-edit').live('click', function(){
			var ul = $(this).parents('ul:first').attr('id');
			var li = $(this).parents('li');
			var span = $('span', li).text();
			$(this).parents('label:first').html('<input type="text" id="'+span+'" value="'+span+'" class="edit_value" /><a class="icon-save save_value" class="button button-small" href="javascript:void(0);"></a>');
		});
		
		//$('.save_value').live('click', function(e){
		$('.sc_option').on('click', '.save_value', function(e){
			e.preventDefault();
			var ul = $(this).parents('ul:first').attr('id');
			var li = $(this).parents('li:first');
			var input = $(this).siblings('.edit_value');
			var value = $(input).val();
			var id = $(input).attr('id');
			var html = '<i class="icon-sort"></i><span>'+value+'</span><i class="icon-trash"></i><i class="icon-edit"></i>';
			
			if( ! value) return sc._msg('Please enter value to save');
			else if(value == id) return $(this).parents('label:first').html(html);
			
			/** Validate value */
			var old_key = sc.get_path(ul)+'.'+id;
			if( ! sc.keySearch(sc.symptoms, old_key)) return sc._msg('Invalid selection, please try again.');
			
			var new_key = sc.get_path(ul)+'.'+value;
			
			eval('sc.symptoms["'+new_key.replace(/\./g, '"]["')+'"] = sc.symptoms["'+old_key.replace(/\./g, '"]["')+'"]; delete sc.symptoms["'+old_key.replace(/\./g, '"]["')+'"]');
			$(this).parents('label:first').html(html);
			$(li).attr('id', new_key).trigger('click');
		});
		
		$('#save_changes').click(function(e){
			e.preventDefault();
			$('.spinner').css('display', 'inline');
			$('#sc_msg').css('display', 'none');
			var stringify = JSON.stringify(sc.symptoms);
			jQuery.post(ajaxurl, {'action':'symptom_checker','symptoms':stringify}, function(response) {
				$('.spinner').css('display', 'none');
				sc._msg(response);
			});
		});
		
		$('.multiselect-checkboxes').sortable({'containment':'.multiselect', update:function(){
				var ul = $(this).attr('id'), myID = parseInt(sc.listID(ul));
			}});
	},
	
	listID : function(str)
	{
		return parseInt(str.replace(/list-/,''));
	},
	
	unselect : function(start)
	{
		for(i=start;i<=4;i++){
			$('#list-'+i).html('');
			delete sc.selected['list-'+(i - 1)];
		}
	},
		
	del_value : function(value, xpath)
	{
		xpath = (xpath) ? xpath : sc.get_path();
		var path = 'sc.symptoms["'+xpath.replace(/\./g, '"]["')+'"]["'+value+'"]';
		
		if( ! sc.keySearch(sc.symptoms, xpath)) return sc._msg('The option is not found, please try again.');
		else eval('delete sc.symptoms["'+xpath.replace(/\./g, '"]["')+'"]["'+value+'"]');
	},
	
	add_value : function(value, xpath)
	{
		xpath = (xpath) ? xpath : sc.get_path();
		var path = 'sc.symptoms["'+xpath.replace(/\./g, '"]["')+'"]["'+value+'"]';
		if( ! sc.keySearch(sc.symptoms, xpath)) return sc._msg('Invalid selection, please try again.');
		else if(eval(path)) return sc._msg('The option is already exists.');
		else{
			
			if(xpath.split('.').length >= 5) return eval('sc.symptoms["'+xpath.replace(/\./g, '"]["')+'"] = ["'+value+'"]');
			else return eval('sc.symptoms["'+xpath.replace(/\./g, '"]["')+'"]["'+value+'"] = {}');
		}
	},
	
	get_path : function(not)
	{
		var path = [sc.gender, sc.view];
		var stop = false
		$.each(sc.selected, function(k, v){
			if(not == k) stop = true;
			else if( ! stop) path.push(v);
		});
		
		return path.join('.');
	},
	
	_msg : function(msg, type)
	{
		type = (type) ? type : 'error';
		$('#sc_msg').html('<span class="'+type+'">'+msg+'</span>').fadeIn('slow');
	},
	
	keySearch : function(obj, path)
	{
		var keys = path.split('.');
		var keyExists = function(obj,keyList)
		{ 
			var cur = keyList.shift();
			if(obj.hasOwnProperty(cur))
			{
				if(keyList.length <= 0)
					return obj[cur];
				else
					return keyExists(obj[cur],keyList);
			}else
				return false;
		};
		
		if(obj && typeof obj == "object" && keys.length > 0)
			return keyExists(obj,keys);
		else
			return false;
	},
	
	update_list : function(id, xpath, refresh)
	{
		if(refresh) $('.multiselect li').remove();
		$('#sc_msg').fadeOut('medium');
				
		var options = sc.keySearch(sc.symptoms, xpath);

		if(options)
		{
			var html = '';
			$.each(options, function(k,v){
				k = (typeof(v) == 'string') ? v : k;
				html += '<li id="'+xpath+'.'+k+'" class="sc_option"><label for="multiselect-'+id+'-'+k+'"><i class="icon-sort"></i><span>'+k+'</span><i class="icon-trash"></i><i class="icon-edit"></i></label></li>';
			});
			
			$('#'+id).html(html);
		}
	}
};

sc.init();

});